//初始化播放器
function initPlayer() {
  $("#courseKeyWordsInfo").html(AUTO_START_TIMER + "秒后自动关闭");

  currentNum = parseInt(getQueryValue("position"));

  totalNum = parseInt(getQueryValue("totalNum"));

  var tmpVideoPath = setVideoPath();

  videoObject = {
    container: "#video1",

    variable: "player",

    autoplay: false,

    flashplayer: false,

    poster: posterURL,

    loaded: "loadedHandler",

    video: tmpVideoPath,
  };

  player = new ckplayer(videoObject);
}

//视频加载媒体信息
function loadedHandler() {
  //changePanelSize(20,40,960,540);

  //setInitTitle();

  startKeyWordsTimer();

  player.addListener("time", timeHandler);

  player.addListener("pause", onVideoPauseHandler); //监听播放时间

  player.addListener("play", onVideoPlayHandler); //监听播放时间

  player.addListener("ended", onVideoPlayEndHandler);

  player.addListener("seeked", onSeekEndEndHandler);

  player.addListener("duration", onDurationHandler); //监听播放时间

  player.addListener("full", onVideoFull); //监听全屏
}

//获取媒体信息
function onDurationHandler() {
  var metaData = player.getMetaDate();

  var duration = parseInt(metaData["duration"]);

  totalDuration = duration;

  videoDuration = duration;

  if (HAS_RATE) $("#playRateBorder").show();
  // $("#loadingMask").remove();

  $(".totalTimeLabel").html(getTimeEmt(duration));

  /* 	 if(!isNaN(lastlocation))
            beginStudy(lastlocation);

     else
            beginStudy(0);    */
}

function onVideoFull(e) {
  if (e === true) {
    isVideoFull = true;

    player.changeControlBarShow(true);
  } else {
    isVideoFull = false;

    player.changeControlBarShow(false);
  }
}

//关闭遮罩
function closeMask() {
  $("#loadingMask").hide();
}

//视频暂停
function setVideoPause() {
  //player.fullScreen();

  player.videoPause();
}

//视频播放
function setVideoPlay() {
  player.videoPlay();
}

//修改音量
function videoMute() {}

//视频全屏
function videoFull() {
  player.fullScreen();
}

function showPlayRatePanel() {
  if ($("#playRateList").is(":visible")) {
    $("#playRateList").hide();
  } else {
    $("#playRateList").show();
  }
}

//下一节
function changeURL() {
  /* alert("currentNum"+currentNum);

	if(currentNum<totalNum)
	{
		parent.startNext();

	} */
  ////playNewVideo();
}

function changeSound(volumn) {
  player.changeVolume(volumn);
}

//关键词页面倒计时
function startKeyWordsTimer() {
  if (AUTO_START_TIMER != 0) {
    keyWordsCountTimer = window.setInterval(startKeyWord, 1000);

    player.changeControlBarShow(false);
  } else {
    keyWordsLoaded = true;

    startVideoPlay();
  }
}

function startKeyWord() {
  if (AUTO_START_TIMER != 0) {
    $("#courseKeyWordsInfo").html(+AUTO_START_TIMER + "秒后自动关闭");

    AUTO_START_TIMER -= 1;
  } else {
    keyWordsLoaded = true;

    clearInterval(keyWordsCountTimer);

    if (!firstLoad) {
      startVideoPlay();

      firstLoad = true;
    } else {
      startMask();
    }
  }
}

function startVideoPlay() {
  if (!isNaN(lastlocation)) beginStudy(lastlocation);
  else beginStudy(0);
}

//更新时间点
function timeHandler(time) {
  currentime = parseInt(time);
}

//监控视频暂停
function onVideoPauseHandler() {
  if (keyWordsLoaded) {
    videoPause = true;

    sco_computeTime();

    if (hasKeyWords) $("#loadingMask").show();

    $("#pauseButton").hide();

    $("#playButton").show();

    if (ad_enabled && !ad_show) {
      showAdArea();
    }

    if (!isVideoFull) player.changeControlBarShow(false);
  }
}

//监控视频播放
function onVideoPlayHandler() {
  $("#loadingMask").hide();

  $("#playButton").hide();

  $("#pauseButton").show();

  $("#adArea").hide();

  ad_show = false;

  if (videoPause) {
    videoPause = false;

    sco_startTimer();
  } else {
    videoPause = false;
  }
  if (!isVideoFull) player.changeControlBarShow(false);
}

//监控视频播放结束
function onVideoPlayEndHandler() {
  window.parent
    .courseFrameFn()
    .doLMSSetValue("cmi.core.lesson_status", "completed");

  var sessionTime = parseInt(totalSessionTime) + parseInt(TIME_COMPENSATE);

  reSetSessionTime();

  doSetLaunch(
    parseInt(currentime) + ";" + parseInt(sessionTime * PROGRESS_TIMES)
  );

  changeCurrentPlay(0);

  window.setTimeout("setVideoPause()", 500);
}

function onVideoPlayNext() {
  setVideoPause();

  playNewVideo();
}

function playNewVideo() {
  if (currentCourseIndex < course_list.length - 1) {
    resetMask();

    currentCourseIndex++;

    AUTO_START_TIMER = 10;

    var tmpVideoPath = setVideoPath();

    player.newVideo({ autoplay: false, video: tmpVideoPath });

    startKeyWordsTimer();
  }
}

//监控拖动进度条
function onSeekEndEndHandler() {
  ////doOther(player.time);
}

//拖动进度条
function changeCurrentPlay(vt) {
  player.videoSeek(vt);
}

//更新时间点
function onSetTimeLabelUpdate() {
  setCurrentTimeLabel(currentime);

  ////checkTest(currentime)

  setProgressBallPosition(currentime);

  numCounter++;

  if (numCounter > TIME_SESSION * 2) {
    numCounter = 0;

    doSetLocation(currentime);
  }
}

//发送时间点
function doSetLocation(time) {
  var sessionTime = 0;

  if (videoPause) {
    sessionTime = parseInt(totalSessionTime);

    reSetSessionTime();
  } else {
    sco_computeTime();

    sessionTime = parseInt(totalSessionTime);

    reSetSessionTime();

    window.setTimeout(sco_startTimer, 100);
  }

  SENDING_COUNT = SENDING_COUNT + 1;

  sessionTime =
    sessionTime <= TIME_SESSION_MAX ? sessionTime + 1 : TIME_SESSION_MAX + 1;

  doSetLaunch(
    parseInt(time) +
      ";" +
      parseInt(sessionTime * PROGRESS_TIMES * CURRENT_RATE) +
      ";" +
      SENDING_COUNT +
      "||" +
      CURRENT_DATE_TIME
  );
}

//首次发送时间点
function setFisrtSession() {
  doSetLaunch(parseInt(lastlocation) + ";5");
}

function resetAutoStop() {
  pauseFromInner = false;

  setVideoPlay();

  auto_stop_timer = setTimeout(onAutoStopFunction, AUTO_STOP_TIME);
}

//自动暂停处理
function onAutoStopFunction() {
  pauseFromInner = true;

  setVideoPause();

  window.parent
    .courseFrameFn()
    .ALTMESSAGE(
      "您已连续播放" +
        parseInt(AUTO_STOP_TIME / 60000) +
        "分钟，点击“确定”继续！",
      "温馨提示",
      resetAutoStop
    );
}

//设置时间标签
function setCurrentTimeLabel(time) {
  var t = getTimeEmt(time);

  $("#currentTimeLabel").html(
    getTimeEmt(time) + " | " + getTimeEmt(totalDuration)
  );
}

//设置滚动珠位置
function setProgressBallPosition(time) {
  var position = parseInt(
    (time / totalDuration) * $("#sliderBackground").width()
  );

  $("#sliderProgress").css("width", position);

  $("#sliderBall").css("left", position - 13);
}

//弹出考题(功能预留)
function checkTest(time) {
  if (parent.hasTest) {
    if (testLoaded && testHided) {
      for (var i = 0; i < testTimeArray.length; i++) {
        if (
          Math.abs(parseInt(time) - parseInt(testTimeArray[i])) < 2 &&
          testStateArray[i] != "dirty"
        ) {
          showTestPanel(i);

          break;
        }
      }
    }
  }
}

//拖动进度条
function changeVideoPlay(time) {
  var percent = parseInt((time / 100) * totalDuration);

  if (enableDrag) changeCurrentPlay(percent);
}

function resetMask() {
  $(".mainPanel").css("pointer-events", "none");

  $("#maskCloseButton").hide();

  $("#courseKeyWordsInfo").show();

  if (hasKeyWords) $("#loadingMask").show();
}

function startMask() {
  $(".mainPanel").css("pointer-events", "auto");

  $("#maskCloseButton").show();

  $("#courseKeyWordsInfo").hide();

  setVideoPlay();
}

//显示倍速面板
function showPlayRatePanel() {
  if ($("#playRateList").is(":visible")) {
    $("#playRateList").hide();
  } else {
    $("#playRateList").show();
  }
}

function changeVideoPlayRate(rate) {
  // player.changePlaybackRate(2);

  document.querySelector("video").playbackRate = rate;

  CURRENT_RATE = rate;

  $("#playRateList").hide();
}

function onSetNewTimerLabelUpdate() {
  setCurrentTimeLabel(currentime);

  setProgressBallPosition(currentime);

  var date = new Date();

  var leftTime = Math.round((endTime - Date.now()) / 1000);

  if (leftTime <= 0) {
    clearInterval(dateIntervalTimer);

    doSetLocation(currentime);

    /* var justTestDate = timestampToDatetime(new Date().getTime());
	  
	   console.log("justTestDate"+justTestDate); */

    reSetTimerSetting();
  }
}

function reSetTimerSetting() {
  left_time_session = TIME_SESSION * 1000;

  endTime = Date.now() + left_time_session;

  dateIntervalTimer = window.setInterval(onSetNewTimerLabelUpdate, 1000);
}

//开始学习
function beginStudy(startTime) {
  //$("#loadingMask").css("height",($(".mainPanel").height()-60)+'px');

  startMask();

  lastlocation = startTime;

  player.changeControlBarShow(true);

  setProgressBallPosition(startTime);

  reSetTimerSetting();

  ////soleTimer=window.setInterval(onSetTimeLabelUpdate,500);

  window.setTimeout(setFisrtSession, 6000);

  if (lastlocation != 0) changeCurrentPlay(lastlocation);
}
